package com.dff.jrfw.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;

import com.dff.jrfw.common.Constant;
import com.dff.jrfw.jsbridge.BrowserClient;
import com.dff.jrfw.utils.ToastUtil;

public class WebPreloadService extends Service {

    public static MutableLiveData<Boolean> isPrepared = new MutableLiveData<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private long startTime = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (isPrepared.getValue() == null) {
            WebView w1 = new WebView(this);
            WebSettings ws1 = w1.getSettings();
            ws1.setDomStorageEnabled(true);
            ws1.setAppCacheEnabled(true);
            ws1.setCacheMode(WebSettings.LOAD_NO_CACHE);
            ws1.setDatabaseEnabled(true);
            ws1.setAllowFileAccess(true);
            ws1.setJavaScriptEnabled(true);
            w1.loadUrl(Constant.APP_H5);
            WebView w2 = new WebView(this);
            WebSettings ws2 = w1.getSettings();
            ws2.setDomStorageEnabled(true);
            ws2.setAppCacheEnabled(true);
            ws2.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            ws2.setDatabaseEnabled(true);
            ws2.setAllowFileAccess(true);
            ws2.setJavaScriptEnabled(true);
            w2.setWebViewClient(new BrowserClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    startTime = System.currentTimeMillis();
                    Log.d("ttt", "onPageStarted");
                    isPrepared.postValue(false);
                }

                @Override
                public void onPageCommitVisible(WebView view, String url) {
                    super.onPageCommitVisible(view, url);
                    Log.d("ttt", "onPageCommitVisible");
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    Log.d("ttt", "onPageFinished");
//                    ToastUtil.toast("预加载完成，耗时" + (System.currentTimeMillis() - startTime) + "ms");
                    isPrepared.postValue(true);
                }
            });
            w2.loadUrl(Constant.APP_H5);
        }
        return super.onStartCommand(intent, flags, startId);
    }
}
